package com.hzhc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzhc.entity.RouterHis;
import com.hzhc.enumBean.ResultUtilCodeEnum;
import com.hzhc.mapper.RouterHisMapper;
import com.hzhc.service.RouterHisService;
import com.hzhc.utils.ResultUtil;
import com.hzhc.vo.RouterHisVo;
import lombok.RequiredArgsConstructor;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 路由搜索历史 服务实现类
 * </p>
 *
 * @author huangp
 * @since 2024-06-29
 */
@Service
@RequiredArgsConstructor
public class RouterHisServiceImpl extends ServiceImpl<RouterHisMapper, RouterHis> implements RouterHisService {

    @Override
    public List<RouterHis> getList(Page<RouterHis> pagination, RouterHisVo vo) {
        IPage<RouterHis> iPage = baseMapper.getList(pagination, vo);
        return iPage.getRecords();
    }

    @Override
    public ResultUtil<Boolean> saveOrUpdateRet(RouterHis vo) {
        vo.setAccessNum(1L);
        LambdaQueryWrapper<RouterHis> wrapper = getWrapper(vo);
        RouterHis routerHis = getOne(wrapper);
        if(routerHis != null){
            vo.setId(routerHis.getId());
            vo.setAccessNum(routerHis.getAccessNum() + 1);
        }
        vo.setAccessTime(LocalDateTime.now());
        boolean b = saveOrUpdate(vo);
        return ResultUtil.build(b,b? ResultUtilCodeEnum.SUCCESS : ResultUtilCodeEnum.FAIL);
    }

    private LambdaQueryWrapper<RouterHis> getWrapper(RouterHis vo){
        LambdaQueryWrapper<RouterHis> wrapper = Wrappers.<RouterHis>lambdaQuery()
                .eq(vo.getPortId() != null, RouterHis::getPortId, vo.getPortId())
                .eq(vo.getMenuId() != null, RouterHis::getMenuId, vo.getMenuId())
                .orderByDesc(RouterHis::getAccessTime);
        return wrapper;
    }

}
